package com.bci.pwtz.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.exception.PwtzException;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.Dyxl;
import com.bci.pwtz.mysql.model.Pdbyq;
import com.bci.pwtz.mysql.model.Zsbyq;
import com.bci.pwtz.service.BusinessCommonService;
import com.bci.pwtz.service.DyxlService;
import com.bci.pwtz.service.PdbyqService;
import com.bci.pwtz.service.ZsbyqService;

@Controller
@RequestMapping("/user/dyxl")
public class DyxlController extends AbstractController{
	@Autowired
    private PdbyqService pdbyqService;
	@Autowired
    private DyxlService dyxlService;
	@Autowired
	private ZsbyqService zsbyqService;
	@Autowired
    private BusinessCommonService businessCommonService;
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public PaginationList<Dyxl> list(int deviceType,String transformerCode, String deviceName, int pageSize, int pageNo) throws PwtzException
    {

        PaginationList<Dyxl> list = new PaginationList<Dyxl>();
        try
        {
        	Long companyid = getLastCompanyId();
            if(deviceType==1){
                Pdbyq obj = pdbyqService.load(transformerCode);
                list = dyxlService.selectDyxlByPdbyq(deviceType, transformerCode, deviceName, companyid, pageSize, pageNo);
                if(list != null){
                    for(int i=0;i<list.getRecords().size();i++){
                        list.getRecords().get(i).setNote(obj.getDevicename());
                    }
                }
            }else{
                Zsbyq obj=zsbyqService.load(transformerCode);
                list = dyxlService.selectDyxlByPdbyq(deviceType, transformerCode, deviceName, companyid, pageSize, pageNo);
                if(list != null){
                    for(int i=0;i<list.getRecords().size();i++){
                        list.getRecords().get(i).setNote(obj.getDevicename());
                    }
                }
            }
            
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
        return list;
    }
	@RequestMapping(value = "/edite", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> edite(String data)
    {
        Map<String, String> map = new HashMap<String, String>();
        try
        {
            //data=java.net.URLDecoder.decode(data,"UTF-8");
            String [] list=decodeURL(data.split("&"));
            				for(int i=0;i<list.length;i++){
				    String[] array=list[i].split("=");
				    if(array.length==1){
				        map.put(array[0], "");
				    }else{
				        map.put(array[0], array[1]);
				    }
				}
				int retCount = businessCommonService.getCountByDeviceName(getLastCompanyId(),(long)AbstractController.低压线路, map.get("devicename"),map.get("deviceid"));
				if(retCount>0){
				    map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "名称已存在！");
				    return map;
				}
				CompanyUser user=(CompanyUser) session.getAttribute("user");
            Dyxl device=new Dyxl();
            device.setDeviceid(map.get("deviceid"));
            device.setDevicename(map.get("devicename"));
            device.setAssetnumber(map.get("assetnumber"));
            device.setAssetsnature(map.get("assetsnature"));
            device.setAssetunit(map.get("assetunit"));
            device.setCommissioningdate(map.get("commissioningdate"));
            device.setCompanyid(user.getLastCompanyId());
            device.setCreateid(user.getCompanyUserId());
            device.setDevicenumber(map.get("devicenumber"));
            device.setEquipmentstate(map.get("equipmentstate"));
            device.setLastoperatorid(user.getCompanyUserId());
            device.setLocalcity(map.get("localcity"));
            device.setMaintenanceteam(map.get("maintenanceteam"));
            device.setNote(map.get("note"));
            device.setOperationstate(map.get("operationstate"));
            device.setOperationunit(map.get("operationunit"));
            device.setSyncstatus(0);
            device.setVoltagelevel(map.get("voltagelevel"));
            device.setDevicetype(PwtzUtils.passInt(map.get("devicetype")));
            device.setTransformercode(map.get("transformercode"));
            device.setCablelength(PwtzUtils.passDouble(map.get("cablelength")));
            device.setEquipmentowner(map.get("equipmentowner"));
            device.setLinetype(map.get("linetype"));
            device.setOverheadlinelength(PwtzUtils.passDouble(map.get("overheadlinelength")));
            device.setTotallinelength(PwtzUtils.passDouble(map.get("totallinelength")));
            int ret = dyxlService.update(device);
            if (ret > 0)
            {
                setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.低压线路, AbstractController.update, "修改低压线路["+device.getDevicename()+"]成功", getUserId());
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "编辑低压线路成功");
            }
            else
            {
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "编辑低压线路失败");
            }
        }
        catch (PwtzDatabaseException e)
        {
            map = packageException(e);
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping(value = "/load", method = RequestMethod.POST)
    @ResponseBody
    public Dyxl load(String deviceId) throws PwtzException
    {
        Dyxl dyxl = null;
        try
        {
            if (null != deviceId)
            {
                dyxl = dyxlService.load(deviceId);
            }
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
        return dyxl;
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> add(String data)
    {
        Map<String, String> map = new HashMap<String, String>();
        try
        {
            //data=java.net.URLDecoder.decode(data,"UTF-8");
            String [] list=decodeURL(data.split("&"));
            for(int i=0;i<list.length;i++){
                String[] array=list[i].split("=");
                if(array.length==1){
                    map.put(array[0], "");
                }else{
                    map.put(array[0], array[1]);
                }
            }
            int retCount = businessCommonService.getCountByDeviceName(getLastCompanyId(),(long)AbstractController.低压线路, map.get("devicename"));
            if(retCount>0){
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "名称已存在！");
                return map;
            }
            CompanyUser user=(CompanyUser) session.getAttribute("user");
            Dyxl device=new Dyxl();
            UUID uuid=UUID.randomUUID();
            device.setDeviceid(uuid.toString());
            device.setDevicename(map.get("devicename"));
            device.setAssetnumber(map.get("assetnumber"));
            device.setAssetsnature(map.get("assetsnature"));
            device.setAssetunit(map.get("assetunit"));
            device.setCommissioningdate(map.get("commissioningdate"));
            device.setCompanyid(user.getLastCompanyId());
            device.setCreateid(user.getCompanyUserId());
            device.setDevicenumber(map.get("devicenumber"));
            device.setEquipmentstate(map.get("equipmentstate"));
            device.setLastoperatorid(user.getCompanyUserId());
            device.setLocalcity(map.get("localcity"));
            device.setMaintenanceteam(map.get("maintenanceteam"));
            device.setNote(map.get("note"));
            device.setOperationstate(map.get("operationstate"));
            device.setOperationunit(map.get("operationunit"));
            device.setSyncstatus(0);
            device.setVoltagelevel(map.get("voltagelevel"));
            device.setDevicetype(PwtzUtils.passInt(map.get("devicetype")));
            device.setTransformercode(map.get("transformercode"));
            device.setCablelength(PwtzUtils.passDouble(map.get("cablelength")));
            device.setEquipmentowner(map.get("equipmentowner"));
            device.setLinetype(map.get("linetype"));
            device.setOverheadlinelength(PwtzUtils.passDouble(map.get("overheadlinelength")));
            device.setTotallinelength(PwtzUtils.passDouble(map.get("totallinelength")));
            device = dyxlService.add(device);
            if (device !=null)
            {
                setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.低压线路, AbstractController.add, "添加低压线路["+device.getDevicename()+"]成功", getUserId());
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "添加低压线路成功");
            }
            else
            {
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "添加低压线路失败");
            }
        }
        catch (PwtzDatabaseException e)
        {
            map = packageException(e);
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }
    
    @RequestMapping(value="dlist",method=RequestMethod.POST)
    @ResponseBody
    public List<Dyxl> getList(Long companyId,int devicetype,String transformercode){
        List<Dyxl> list=new ArrayList<Dyxl>();
        try{
            PaginationList<Dyxl> plist=dyxlService.findDyxl(null, companyId, 1, null,devicetype,transformercode, null, null, 0, 0);
            if(plist!=null&&plist.getTotalRecord()>0){
                list=plist.getRecords();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }
    
    @RequestMapping(value="/delete",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> delete(String deviceid){
        Map<String,String> map=new HashMap<String, String>();
        int result=0;
        try
        {
            Dyxl device=dyxlService.load(deviceid);
            result=dyxlService.delete(deviceid);
            if (result>0&&device!=null)
            {
                setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.低压线路, AbstractController.delete, "删除低压线路["+device.getDevicename()+"]成功", getUserId());
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "删除低压线路成功");
            }
            else
            {
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "删除低压线路失败");
            }
        }
        catch (PwtzDatabaseException e)
        {
            map = packageException(e);
        }
        catch (CanNotDeleteException e)
        {
            map = packageException(e);
        }
        return map;
    }
}
